#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}[$(date '+%Y-%m-%d %H:%M:%S')] ${message}${NC}"
}

echo "========================================"
echo "      清算服务一键部署脚本"
echo "========================================"
echo



# 检查Python环境
print_message $BLUE "[步骤1] 检查Python环境..."
if ! command -v python3 &> /dev/null; then
    print_message $RED "[错误] 未找到Python3环境，请先安装Python 3.8+"
    echo "Ubuntu/Debian: sudo apt-get install python3 python3-pip"
    echo "CentOS/RHEL: sudo yum install python3 python3-pip"
    echo "macOS: brew install python3"
    exit 1
fi

print_message $GREEN "[成功] Python3环境检查通过"
PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
print_message $BLUE "[信息] Python版本: $PYTHON_VERSION"
echo

# 检查pip环境
print_message $BLUE "[步骤2] 检查pip环境..."
if ! command -v pip3 &> /dev/null; then
    print_message $RED "[错误] 未找到pip3，请重新安装Python3"
    exit 1
fi

print_message $GREEN "[成功] pip3环境检查通过"
PIP_VERSION=$(pip3 --version | awk '{print $2}')
print_message $BLUE "[信息] pip版本: $PIP_VERSION"
echo

# 创建必要的目录
print_message $BLUE "[步骤3] 创建必要的目录..."
directories=("logs" "temp_downloads" "charts" "monitor/logs")
for dir in "${directories[@]}"; do
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
        print_message $BLUE "[信息] 创建目录: $dir"
    fi
done
print_message $GREEN "[成功] 目录创建完成"
echo

# 安装项目依赖
print_message $BLUE "[步骤4] 安装项目依赖..."
print_message $BLUE "[信息] 正在安装依赖包，请稍候..."
if [ -f "requirements.txt" ]; then
    pip3 install -r requirements.txt
    if [ $? -ne 0 ]; then
        print_message $RED "[错误] 依赖安装失败"
        echo "请检查网络连接或手动运行: pip3 install -r requirements.txt"
        exit 1
    fi
else
    print_message $RED "[错误] 未找到requirements.txt文件"
    exit 1
fi
print_message $GREEN "[成功] 项目依赖安装完成"
echo

# 检查配置文件
print_message $BLUE "[步骤5] 检查配置文件..."
if [ ! -f "config.py" ]; then
    print_message $YELLOW "[警告] 未找到config.py文件，请确保配置文件存在"
    echo "请参考config.example.py创建配置文件"
    read -p "按回车键继续..."
else
    print_message $GREEN "[成功] 配置文件检查通过"
fi
echo

# 检查端口占用
print_message $BLUE "[步骤6] 检查端口占用..."
if command -v netstat &> /dev/null; then
    if netstat -tuln 2>/dev/null | grep -q ":8088 "; then
        print_message $YELLOW "[警告] 端口8088已被占用"
        echo "请检查是否有其他服务正在使用此端口"
        read -p "是否继续部署? (y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_message $BLUE "[信息] 部署已取消"
            exit 0
        fi
    else
        print_message $GREEN "[成功] 端口8088可用"
    fi
else
    print_message $YELLOW "[警告] 无法检查端口状态，请手动确认端口8088可用"
fi
echo

# 启动服务
print_message $BLUE "[步骤7] 启动清算服务..."
print_message $BLUE "[信息] 服务将在后台启动"
print_message $BLUE "[信息] 服务地址: http://localhost:8088"
print_message $BLUE "[信息] API文档: http://localhost:8088/docs"
echo

# 启动主服务
nohup python3 main.py > logs/app.log 2>&1 &
MAIN_SERVICE_PID=$!
print_message $GREEN "[成功] 主服务已启动 (PID: $MAIN_SERVICE_PID)"

# 等待服务启动
print_message $BLUE "[信息] 等待服务启动..."
sleep 10

# 检查服务状态
print_message $BLUE "[步骤8] 检查服务状态..."
if command -v curl &> /dev/null; then
    if curl -s http://localhost:8088/health > /dev/null 2>&1; then
        print_message $GREEN "[成功] 清算服务启动成功"
        print_message $GREEN "[成功] 服务健康检查通过"
    else
        print_message $YELLOW "[警告] 清算服务可能启动失败，请检查日志"
        print_message $BLUE "[信息] 查看日志: tail -f logs/app.log"
    fi
else
    print_message $YELLOW "[警告] 无法检查服务状态，请手动确认"
fi
echo

# 启动监控服务
print_message $BLUE "[步骤9] 启动监控服务..."
if [ -f "monitor/run_service_monitor.sh" ]; then
    cd monitor
    nohup bash run_service_monitor.sh > ../logs/monitor.log 2>&1 &
    MONITOR_PID=$!
    cd ..
    print_message $GREEN "[成功] 监控服务已启动 (PID: $MONITOR_PID)"
    print_message $BLUE "[信息] 监控日志: logs/monitor.log"
else
    print_message $YELLOW "[警告] 未找到监控启动脚本"
    # 尝试直接启动监控服务
    if [ -f "monitor/service_monitor.py" ]; then
        cd monitor
        nohup python3 service_monitor.py > ../logs/monitor.log 2>&1 &
        MONITOR_PID=$!
        cd ..
        print_message $GREEN "[成功] 监控服务已启动 (PID: $MONITOR_PID)"
        print_message $BLUE "[信息] 监控日志: logs/monitor.log"
    fi
fi
echo

# 保存进程ID
echo "$MAIN_SERVICE_PID" > logs/main_service.pid
echo "$MONITOR_PID" > logs/monitor_service.pid

# 部署完成
echo "========================================"
print_message $GREEN "[完成] 清算服务部署完成！"
echo "========================================"
echo
echo "服务信息:"
echo "- 主服务: http://localhost:8088"
echo "- API文档: http://localhost:8088/docs"
echo "- 健康检查: http://localhost:8088/health"
echo
echo "日志文件:"
echo "- 主服务日志: logs/app.log"
echo "- 监控日志: logs/monitor.log"
echo
echo "进程ID:"
echo "- 主服务PID: $(cat logs/main_service.pid)"
echo "- 监控PID: $(cat logs/monitor_service.pid)"
echo
echo "管理命令:"
echo "- 查看日志: tail -f logs/app.log"
echo "- 停止服务: ./stop.sh"
echo "- 重启服务: ./deploy.sh"
echo "- 查看进程: ps aux | grep python3"
echo
echo "[提示] 服务已在后台运行"
echo

# 询问是否打开浏览器
read -p "是否打开浏览器访问服务? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if command -v xdg-open &> /dev/null; then
        xdg-open http://localhost:8088/docs
    elif command -v open &> /dev/null; then
        open http://localhost:8088/docs
    else
        print_message $YELLOW "[提示] 请手动打开浏览器访问: http://localhost:8088/docs"
    fi
fi

# 创建停止脚本
cat > stop.sh << 'EOF'
#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_message() {
    local color=$1
    local message=$2
    echo -e "${color}[$(date '+%Y-%m-%d %H:%M:%S')] ${message}${NC}"
}

echo "========================================"
echo "      清算服务停止脚本"
echo "========================================"
echo

# 停止主服务
if [ -f "logs/main_service.pid" ]; then
    MAIN_PID=$(cat logs/main_service.pid)
    if [ -n "$MAIN_PID" ] && [ "$MAIN_PID" -eq "$MAIN_PID" ] 2>/dev/null && ps -p $MAIN_PID > /dev/null; then
        print_message $BLUE "[信息] 停止主服务 (PID: $MAIN_PID)..."
        kill $MAIN_PID
        sleep 2
        if [ -n "$MAIN_PID" ] && [ "$MAIN_PID" -eq "$MAIN_PID" ] 2>/dev/null && ps -p $MAIN_PID > /dev/null; then
            print_message $YELLOW "[警告] 强制停止主服务..."
            kill -9 $MAIN_PID
        fi
        print_message $GREEN "[成功] 主服务已停止"
    else
        print_message $YELLOW "[警告] 主服务未运行"
    fi
    rm -f logs/main_service.pid
fi

# 停止监控服务
if [ -f "logs/monitor_service.pid" ]; then
    MONITOR_PID=$(cat logs/monitor_service.pid)
    if [ -n "$MONITOR_PID" ] && [ "$MONITOR_PID" -eq "$MONITOR_PID" ] 2>/dev/null && ps -p $MONITOR_PID > /dev/null; then
        print_message $BLUE "[信息] 停止监控服务 (PID: $MONITOR_PID)..."
        kill $MONITOR_PID
        sleep 2
        if [ -n "$MONITOR_PID" ] && [ "$MONITOR_PID" -eq "$MONITOR_PID" ] 2>/dev/null && ps -p $MONITOR_PID > /dev/null; then
            print_message $YELLOW "[警告] 强制停止监控服务..."
            kill -9 $MONITOR_PID
        fi
        print_message $GREEN "[成功] 监控服务已停止"
    else
        print_message $YELLOW "[警告] 监控服务未运行"
    fi
    rm -f logs/monitor_service.pid
fi

# 检查是否还有相关进程运行
print_message $BLUE "[信息] 检查是否还有相关进程..."
ps aux | grep python3 | grep -E "(main.py|service_monitor.py)" | grep -v grep

if [ $? -eq 0 ]; then
    print_message $YELLOW "[警告] 发现残留进程，请手动检查"
else
    print_message $GREEN "[成功] 所有服务已停止"
fi

echo
echo "[完成] 服务停止完成"
EOF

chmod +x stop.sh

print_message $GREEN "[信息] 停止脚本已创建: stop.sh"
print_message $GREEN "[信息] 部署完成！"